package orm

import (
	"gorm.io/gorm"
	"hertz_demo/orm/db"
	"hertz_demo/orm/models"
)

func FavorVideo(user *models.User, videoId int64) error {
	relation := db.FavouriteRelation{
		UserId:  user.ID,
		VideoId: videoId,
	}
	err := db.DB.Transaction(func(tx *gorm.DB) error {
		var relationId int64 = 0
		tx.Raw("select `id` from `favourite_relations` where `user_id`=? and `video_id`=? and is_del=false for update",
			user.ID, videoId).Scan(&relationId)
		if relationId != 0 {
			return nil
		}
		if err := tx.Model(&db.FavouriteRelation{}).Create(&relation).Error; err != nil {
			return err
		}
		if err := tx.Model(&db.Video{}).Where("id=?", videoId).Update("favourite_count", gorm.Expr("favourite_count + ?", 1)).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}

func DisFavorVideo(user *models.User, videoId int64) error {
	err := db.DB.Transaction(func(tx *gorm.DB) error {
		var relationId int64 = 0
		tx.Raw("select `id` from `favourite_relations` where `user_id`=? and `video_id`=? and is_del=false for update",
			user.ID, videoId).Scan(&relationId)
		if relationId == 0 {
			return nil
		}
		if err := tx.Model(&db.FavouriteRelation{}).Where("id=?", relationId).Update("is_del", true).Error; err != nil {
			return err
		}
		if err := tx.Model(&db.Video{}).Where("id=?", videoId).Update("favourite_count", gorm.Expr("favourite_count - ?", 1)).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}

func GetFavouriteList(user *models.User) ([]models.Video, error) {
	var resultList []models.Video
	var favouriteList []int64
	if err := db.DB.Model(&db.FavouriteRelation{}).Select("video_id").Where("user_id = ?", user.ID).Scan(&favouriteList).Error; err != nil {
		return resultList, err
	}
	var dbVideoList []db.Video
	if err := db.DB.Model(&db.Video{}).Find(&dbVideoList, favouriteList).Error; err != nil {
		return resultList, err
	}
	for _, dbVideo := range dbVideoList {
		video := models.Video{
			ID:             dbVideo.ID,
			Author:         *user,
			Title:          dbVideo.Title,
			PlayUrl:        dbVideo.PlayUrl,
			CoverUrl:       dbVideo.CoverUrl,
			FavoriteCount: dbVideo.FavouriteCount,
			CommentCount:   dbVideo.CommentCount,
			IsFavorite:    true,
		}
		resultList = append(resultList, video)
	}
	return resultList, nil
}
